package com.example.lets;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.bmob.btp.callback.UploadListener;
import com.gc.materialdesign.widgets.SnackBar;
import com.widget.CircleImageView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class MeActivity extends BaseActivity {
    private SelectPicPopupWindow selWindow;
    private Uri photoUri = null;
    private String fileName = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me);
        User curUser = BmobUser.getCurrentUser(MeActivity.this, User.class);

        // 将各个输入框的显示值设置为用户当前的信息，删除后会有提示
        EditText nickName = (EditText) findViewById(R.id.me_change_username);
        nickName.setText(curUser.getNickname());
        EditText Tag1 = (EditText) findViewById(R.id.me_change_tag1);
        Tag1.setText(curUser.getTag1());
        EditText Tag2 = (EditText) findViewById(R.id.me_change_tag2);
        Tag2.setText(curUser.getTag2());
        EditText Tag3 = (EditText) findViewById(R.id.me_change_tag3);
        Tag3.setText(curUser.getTag3());
        ((EditText) findViewById(R.id.me_description)).setText(curUser.getDescription());
        final CheckBox male = (CheckBox) findViewById(R.id.me_change_male);
        final CheckBox female = (CheckBox) findViewById(R.id.me_change_female);
        if (curUser.getGender().equals("male")) male.setChecked(true);
        else female.setChecked(true);
        EditText age = (EditText) findViewById(R.id.me_change_age);
        age.setText(String.valueOf(curUser.getAge()));

        // checkbox male & female
        female.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (male.isChecked()) {
                    male.setChecked(false);
                }
            }
        });
        male.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (female.isChecked()) {
                    female.setChecked(false);
                }
            }
        });

        // 若有头像则下载并显示，否则点击上传头像按钮的事件
        String headFileName = curUser.getPicFilename();
        String name[] = headFileName.split("\\.");
        String newFileName = name[0] + "_2_120_0_100." + name[1];
        String cacheThumbnailPath = BmobPro.getInstance(MeActivity.this).getCacheThumbnailDir() + "/" + newFileName;

        CircleImageView upload = (CircleImageView) findViewById(R.id.me_portrait);

        upload.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) { // 点击打开资源管理器选择图片
                // 实例化SelectPicPopupWindow
                selWindow = new SelectPicPopupWindow(MeActivity.this, new OnClickListener() {
                    // 为弹出窗口实现监听类
                    public void onClick(View v) {
                        selWindow.dismiss();

                        int id = v.getId();
                        if (id == R.id.btn_take_photo) {

                            SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
                            String filename = "Lets_Head_" + timeStampFormat.format(new Date());
                            ContentValues values = new ContentValues();
                            values.put(Media.TITLE, filename);
                            Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                            startActivityForResult(intent1, 1);

                        } else if (id == R.id.btn_pick_photo) {

                            Intent intent2 = new Intent();
                            // 开启Pictures画面Type设定为image
                            intent2.setType("image/*");
                            // 使用Intent.ACTION_GET_CONTENT这个Action
                            intent2.setAction(Intent.ACTION_GET_CONTENT);
                            // 取得相片后返回本画面
                            startActivityForResult(intent2, 2);

                        } else {

                            Log.i("bmob", "undefined button");
                            new SnackBar(MeActivity.this, "未定义的按钮", null, null).show();
                        }
                    }
                });

                selWindow.showAtLocation(MeActivity.this.findViewById(R.id.me_portrait),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });

        if (headFileName.equals("")) { // 点击上传头像按钮的事件


        } else { // 若有头像则先检查缓存下载并显示

            if ((new File(cacheThumbnailPath)).exists()) {

                Log.i("bmob", "成功加载缓存" + cacheThumbnailPath);
                Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
                CircleImageView cImageView = (CircleImageView) findViewById(R.id.me_portrait);
                cImageView.setImageBitmap(bm); // 将Bitmap设定到CircleImageView

            } else {
                BTPFileResponse response = BmobProFile.getInstance(MeActivity.this).download(headFileName, new DownloadListener() {

                    @Override
                    public void onSuccess(String fullPath) {
                        Log.i("bmob", "下载成功：" + fullPath);
                        // 根据下载的图片在本地生成缩略图
                        BmobProFile.getInstance(MeActivity.this).getLocalThumbnail(fullPath, 2, new LocalThumbnailListener() {

                            @Override
                            public void onSuccess(String thumbnailPath) {
                                Log.i("bmob", "localThumbnail-->生成后的缩略图路径 :" + thumbnailPath);
                                Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
                                CircleImageView cImageView = (CircleImageView) findViewById(R.id.me_portrait);
                                cImageView.setImageBitmap(bm); // 将Bitmap设定到CircleImageView
                            }

                            @Override
                            public void onError(int statuscode, String errormsg) {
                                Log.i("bmob", "localThumbnail-->生成缩略图失败 :" + statuscode + "," + errormsg);
                            }
                        });
                    }

                    @Override
                    public void onProgress(String localPath, int percent) {
                        Log.i("bmob", "download-->onProgress :" + percent);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                        Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
                        new SnackBar(MeActivity.this, "下载出错：" + statuscode + "--" + errormsg,
                                null, null).show();
                    }
                });

            }
        }

        // toolbar
        Toolbar toolbar = (Toolbar) this.findViewById(R.id.me_toolbar);
        toolbar.setTitle("个人中心");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        toolbar.setNavigationOnClickListener(new Toolbar.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String newNickname = ((EditText) findViewById(R.id.me_change_username)).getText().toString();
                String newTag1 = ((EditText) findViewById(R.id.me_change_tag1)).getText().toString();
                String newTag2 = ((EditText) findViewById(R.id.me_change_tag2)).getText().toString();
                String newTag3 = ((EditText) findViewById(R.id.me_change_tag3)).getText().toString();
                String description = ((EditText) findViewById(R.id.me_description)).getText().toString();
                String gender = ((CheckBox) findViewById(R.id.me_change_male)).isChecked() ? "male" :
                        ((CheckBox) findViewById(R.id.me_change_female)).isChecked() ? "female" : null;
                Integer age = Integer.valueOf("0");

                if (newNickname.equals("")) {
                    new SnackBar(MeActivity.this, "请输入用户名", null, null).show();
                    return false;
                }

                if (newNickname.length() > 12) {
                    new SnackBar(MeActivity.this, "用户昵称过长，请限制在12个字符以内", null, null).show();
                    return false;
                }

                if (gender == null) {
                    new SnackBar(MeActivity.this, "性别不明", null, null).show();
                    return false;
                }

                try {
                    age = Integer.parseInt(((EditText) findViewById(R.id.me_change_age)).getText().
                            toString());
                } catch (NumberFormatException e) {
                    new SnackBar(MeActivity.this, "请输入正确的年龄", null, null).show();
                }

                if (age <= 0 || age >= 100) {
                    new SnackBar(MeActivity.this, "请输入正确的年龄", null, null).show();
                    return false;
                }

                if (newTag1.equals("") || newTag2.equals("") || newTag3.equals("")) {
                    new SnackBar(MeActivity.this, "请将三个兴趣标签填写完整", null, null).show();
                    return false;
                }

                modifyInfo(newNickname, gender, age, newTag1, newTag2, newTag3, description);
                return true;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.me, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void modifyInfo(final String newNickname, String gender, Integer age, String newTag1,
                            String newTag2, String newTag3, String description) {
        BmobUser currentUser = BmobUser.getCurrentUser(MeActivity.this);
        final String id = currentUser.getObjectId();

        final User newUser = new User();

        newUser.setNickname(newNickname);
        newUser.setTag1(newTag1);
        newUser.setTag2(newTag2);
        newUser.setTag3(newTag3);
        newUser.setAge(age);
        newUser.setGender(gender);
        newUser.setDescription(description);

        if (fileName != null) {
            File file = new File(fileName);
            if (!file.exists()) Log.e("bmob", "头像未更新");

            else {
                BmobProFile.getInstance(MeActivity.this).upload(fileName, new UploadListener() {
                    @Override
                    public void onSuccess(String fileName, String url, BmobFile file) {
                        Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
                        newUser.setPicture(file);
                        newUser.setPicFilename(fileName);
                        newUser.update(MeActivity.this, id, new UpdateListener() {
                            @Override
                            public void onFailure(int arg0, String arg1) {
                                new SnackBar(MeActivity.this, "头像完善失败", null, null).show();
                            }

                            @Override
                            public void onSuccess() {
                                new SnackBar(MeActivity.this, "头像完善成功", null, null).show();
                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress) {
                        Log.i("bmob", "onProgress :" + progress);
                    }

                    @Override
                    public void onError(int statuscode, String errormsg) {
                        Log.i("bmob", "文件上传失败：" + errormsg);
                    }
                });
            }
        }

        newUser.update(MeActivity.this, id, new UpdateListener() {

            @Override
            public void onFailure(int arg0, String arg1) {
                new SnackBar(MeActivity.this, "完善失败", null, null).show();
            }

            @Override
            public void onSuccess() {
                new SnackBar(MeActivity.this, "信息更新成功", null, null).show();
                refreshActivitySponsorName(id, newNickname);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        FileOutputStream b = null;
        String path = "/sdcard/Lets/myHead/";
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();

        User curUser = BmobUser.getCurrentUser(this, User.class);
        fileName = path + curUser.getUsername() + "_head.jpg";
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.i("bmob", e.getMessage());
        } finally {
            try {
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        // 这里处理逻辑代码，大家注意：该方法仅适用于2.0或更新版的sdk
        finish();
    }

    public void refreshActivitySponsorName(String sponsorId, final String newNickname) {
        UserActivity ac = new UserActivity();
        ac.setSponsorName("newNickname");
        BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();
        query.addWhereEqualTo("sponsorId", sponsorId);
        query.setLimit(15);

        query.findObjects(this, new FindListener<UserActivity>() {

            @Override
            public void onSuccess(List<UserActivity> object) {
                for (UserActivity activity : object) {
                    String actiId = activity.getObjectId().toString();
                    UserActivity ac = new UserActivity();
                    ac.setSponsorName(newNickname);
                    ac.update(MeActivity.this, actiId, new UpdateListener() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFailure(int code, String msg) {

                        }
                    });
                }
                Intent intent = new Intent(MeActivity.this, HomeActivity.class);
                startActivity(intent);
            }

            @Override
            public void onError(int code, String msg) {
                new SnackBar(MeActivity.this, "更新活动发起者昵称失败", null, null).show();
            }
        });
    }
}
